package edu.umn.actvs;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;

public class EventDBCreator extends SQLiteOpenHelper{

	private static final String dName = "events_user_db";
	private static final String tName = "user_event";
	private static final int dversion = 1;
	private SQLiteStatement insertEvent;
	private SQLiteDatabase db;
	
	public EventDBCreator(Context context) {
		super(context, dName, null, dversion);
		// TODO Auto-generated constructor stub
		Log.w("db", "db initilized");
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		
		this.db = db;
		this.db.execSQL("CREATE TABLE IF NOT EXISTS "+tName+ "(ename TEXT primary key, port integer," +
		" username TEXT, password TEXT)");
		insertEvent = db.compileStatement ("INSERT INTO "+tName+" (ename, port,username,password) "+"VALUES('?',?,'?','?')");
		
		Log.w("db", "inserEvent initilized");
	}

	public void insertEvent(String insertionData){
		// persists user events
		db = this.getWritableDatabase();

		insertEvent = db.compileStatement ("INSERT INTO "+tName+" (ename, port,username,password) "+"VALUES(?,?,?,?)");
		StringTokenizer tokenizer = new StringTokenizer(insertionData,",");
		int i = 1;
		while(tokenizer.hasMoreElements()){
			insertEvent.bindString(i, String.valueOf(tokenizer.nextToken()));
			i++;
		}
		insertEvent.executeInsert();
		db.close();
	}

	public List<String> getAllEvents(){
		db= this.getReadableDatabase();
		List<String> elist = new ArrayList<String>();
		Cursor crs = this.db.query(tName, new String[]{"ename"},
				null, null, null, null, "ename desc");
		while(crs.moveToNext()){
			elist.add(crs.getString(0));
		}
		if(crs != null && !crs.isClosed()){
			crs.close();
		}
		db.close();
		return elist;
	}

	public List<String> getEventInfo(String param){
		db= this.getReadableDatabase();
		List<String> elist = new ArrayList<String>();
		Cursor crs = this.db.query(tName, new String[]{"port","username","password"},
				"ename LIKE ?", new String[]{param}, null,null,null);
		//this is a temporary design: no 2 events have the same ID
		crs.moveToFirst();
		elist.add(crs.getString(0));
		elist.add(crs.getString(1));
		elist.add(crs.getString(2));
		
		if(crs != null && !crs.isClosed()){
			crs.close();
		}
		db= this.getReadableDatabase();
		return elist;
	}

	@Override
	public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
		// TODO Auto-generated method stub

	}

}
